package com.transcoachapp;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Time;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.transcoachapp.adapter.BusStationDepartureTimeAdapter;
import com.transcoachapp.adapter.FerryStationTimeAdapter;
import com.transcoachapp.adapter.StationTimeAdapter;
import com.transcoachapp.data.BusStationTime;
import com.transcoachapp.data.FerryTime;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class FerryTimeActivity extends MainActivity {
	private String ferryId, name;
	private ArrayList<FerryTime> weekDayList = new ArrayList<FerryTime>();
	private ArrayList<FerryTime> saturdayList = new ArrayList<FerryTime>();
	private ArrayList<FerryTime> sundayList = new ArrayList<FerryTime>();
	private FerryStationTimeAdapter adapter1, adapter2, adapter3;
	private ListView listView1, listView2,listView3;
	private ImageButton  backBtn;
	TextView text1, text2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ferry_station_time);
		Bundle extras = getIntent().getExtras();
	    if (extras != null)
	    {
	    	ferryId = extras.getString("ferryId");
	    	name = extras.getString("name");
	    }
	    text2 = (TextView)findViewById(R.id.textView2);
	    text2.setText(name);
		listView1 = (ListView)findViewById(R.id.android_timeWeekDayList);
		listView2 = (ListView)findViewById(R.id.android_timeSaturdayList);
		listView3 = (ListView)findViewById(R.id.android_timeSundayList);
		backBtn = (ImageButton )findViewById(R.id.backButton);
		backBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				FerryTimeActivity.this.finish();
			}
		});
		new HttpTask().execute();
	}

	 public void populateList() {
		 if (weekDayList.size()>0)
			   populateWeekDayList();
		   if (saturdayList.size()>0)
			   populateSaturdayList();
		   if (sundayList.size()>0)
			   populateSundayList();
	 }
	 public void populateWeekDayList(){
	 	 adapter1 = new FerryStationTimeAdapter(this, R.layout.bus_station_time, weekDayList);
		 listView1.setAdapter(adapter1);
	}
	  
	 public void populateSaturdayList(){
		 adapter2 = new FerryStationTimeAdapter(this, R.layout.bus_station_time, saturdayList);
		 listView2.setAdapter(adapter2);
	 }
	 public void populateSundayList(){
		 adapter3 = new FerryStationTimeAdapter(this, R.layout.bus_station_time, sundayList);
		 listView3.setAdapter(adapter3);
	 }
	 
		final class HttpTask extends AsyncTask<Void, Boolean, String> {
			public static final String url = "http://titan.cmpe.boun.edu.tr:8080/TransportationMid/";
			private Context mContext;
			private final ProgressDialog loadingDialog = new ProgressDialog(getDialogContext());

			@Override
			protected String doInBackground(Void... param) {
				publishProgress(true);
				// Creating HTTP client
				HttpClient httpClient = new DefaultHttpClient();
		
				// Creating HTTP Post
				String operation = "getFerryTimeList?ferry_id="+ferryId;
				HttpPost httpPost = new HttpPost(url+operation);
		
				// Building post parameters, key and value pair	
				// Url Encoding the POST parameters
				try {
					//httpPost.setEntity(operation);
					// Making HTTP Request
					HttpResponse response = httpClient.execute(httpPost);
					return EntityUtils.toString(response.getEntity());
		
				} catch (ClientProtocolException e) {
					// writing exception to log
					e.printStackTrace();
		
				} catch (IOException e) {
					// writing exception to log
					e.printStackTrace();
				}
		
				return null;
			}
		
			@Override
			protected void onProgressUpdate(Boolean... progress) {
				FerryTimeActivity.this.setProgressBarIndeterminateVisibility(progress[0]);
			}
			
			@Override
			protected void onPreExecute(){
				super.onPreExecute();
		        loadingDialog.setMessage("Loading ...");
		        loadingDialog.setIndeterminate(false);
		        loadingDialog.setCancelable(false);
		        loadingDialog.show();
			}
			@Override
			protected void onPostExecute(String result) {
				publishProgress(false);

				if(result == null || !result.startsWith("[") || result.equals("[]"))
				{
					if (this.loadingDialog.isShowing())
						this.loadingDialog.dismiss();	
					Intent intent = new Intent();
	                intent.setClass(FerryTimeActivity.this, FerryTimeActivity.class);
	                intent.putExtra("ferryId", ferryId);
	                intent.putExtra("name", name);
					AlertAndFinish(intent, FerryTimeActivity.this);
				
				//	Toast.makeText(getApplicationContext(), (CharSequence)"Server connection error!", Toast.LENGTH_SHORT).show();
					return;
				}
				try
				{
					/////////////////////////////////////////////////////////////////////
					JSONArray jarray = new JSONArray(result);
					for(int i=0;i<jarray.length();i++){
						JSONObject bsd = jarray.getJSONObject(i);
					//	SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
					//	 Date time = (Date)formatter.parse(bsd.getString("time"));
						java.sql.Time time = java.sql.Time.valueOf(bsd.getString("time"));
						FerryTime bsdItem = new FerryTime(Integer.parseInt(bsd.getString("timeId")),
								Integer.parseInt(bsd.getString("ferryId")), bsd.getString("name"),
								time, bsd.getString("direction"), bsd.getString("dayCode"));
						Log.i("---------------", bsdItem.getDayCode()+"   "+bsdItem.getTime().toString());
						
						if(bsdItem.getDayCode().equalsIgnoreCase("H"))
							weekDayList.add(bsdItem);
						else if(bsdItem.getDayCode().equalsIgnoreCase("C"))
							saturdayList.add(bsdItem);
						else
							sundayList.add(bsdItem);
						
						if (this.loadingDialog.isShowing())
							this.loadingDialog.dismiss();
						
							populateList();
					}
		
				} catch (JSONException e) {
					// writing exception to log
					e.printStackTrace();
				} 
			}	
		}
		private Context getDialogContext() {
		    Context context;
		    if (getParent() != null) context = getParent();
		    else context = this;
		    return context;
		}
}
